package com.cb.web.wasf.sample.model;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.persist.Transactional;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.SetJoin;

/**
 * @author CBO
 */
@Transactional
public class RoleManager {

    @Inject
    Provider<EntityManager> entityManagerProvider;
    private static final RoleBO USER_ADMINISTRATION = new RoleBO("USER_ADMINISTRATION", "Administration des utilisateurs");
    private static final List<RoleBO> ALL;

    static {
        ALL = new ArrayList<RoleBO>();
        ALL.add(USER_ADMINISTRATION);
    }

    public List<RoleBO> getAll() {
        return ALL;
    }

    public RoleBO getUserAdministrationRole() {
        return USER_ADMINISTRATION;
    }

    public RoleBO getByName(String name) {
        return entityManagerProvider.get().find(RoleBO.class, name);
    }

    public RoleBO create(String name, String description) {
        RoleBO role = new RoleBO(name, description);
        entityManagerProvider.get().persist(role);
        return role;
    }

    public List<RoleBO> getByAllByUser(UserBO user) {
        CriteriaBuilder cb = entityManagerProvider.get().getCriteriaBuilder();
        CriteriaQuery<RoleBO> query = cb.createQuery(RoleBO.class);
        SetJoin<ProfilBO, UserBO> profilUserJoin = query.from(RoleBO.class).join(RoleBO_.profils).join(ProfilBO_.users);
        query.distinct(true);
        query.where(cb.equal(profilUserJoin.get(UserBO_.id), user.getId()));
        return entityManagerProvider.get().createQuery(query).getResultList();
    }
}
